package org.micro.frame.mybatis.plus.configuration;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.UnderlinedNameConversion;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.BeetlSqlScannerConfigurer;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;

import javax.sql.DataSource;

/**
 * The Base Configuration
 *
 * @author lry
 */
public class BaseConfiguration {

    /**
     * The Build DataSource
     *
     * @return
     */
    protected DataSource buildDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * The Build SqlManagerFactoryBean
     *
     * @param dataSource
     * @param beetlsqlProperties
     * @return
     */
    protected SqlManagerFactoryBean buildSqlManagerFactoryBean(DataSource dataSource, BeetlsqlProperties beetlsqlProperties) {
        BeetlSqlDataSource beetlSqlDataSource = new BeetlSqlDataSource();
        beetlSqlDataSource.setMasterSource(dataSource);

        SqlManagerFactoryBean sqlManagerFactoryBean = new SqlManagerFactoryBean();
        sqlManagerFactoryBean.setCs(beetlSqlDataSource);
        sqlManagerFactoryBean.setDbStyle(new MySqlStyle());
        sqlManagerFactoryBean.setSqlLoader(new ClasspathLoader(beetlsqlProperties.getSqlRoot()));
        sqlManagerFactoryBean.setNc(new UnderlinedNameConversion());
        if (beetlsqlProperties.getDebugInterceptor()) {
            sqlManagerFactoryBean.setInterceptors(new Interceptor[]{new DebugInterceptor()});
        }

        return sqlManagerFactoryBean;
    }

    /**
     * The build BeetlSqlScannerConfigurer
     *
     * @param sqlManagerFactoryBeanName
     * @param beetlsqlProperties
     * @return
     */
    protected BeetlSqlScannerConfigurer buildBeetlSqlScannerConfigurer(
            String sqlManagerFactoryBeanName, BeetlsqlProperties beetlsqlProperties) {
        BeetlSqlScannerConfigurer beetlSqlScannerConfigurer = new BeetlSqlScannerConfigurer();
        beetlSqlScannerConfigurer.setBasePackage(beetlsqlProperties.getBasePackage());
        beetlSqlScannerConfigurer.setDaoSuffix(beetlsqlProperties.getDaoSuffix());
        beetlSqlScannerConfigurer.setSqlManagerFactoryBeanName(sqlManagerFactoryBeanName);
        return beetlSqlScannerConfigurer;
    }

}
